package org.lds.message.center.common.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class ScheduledUtil {

    public static void closableScheduled(long delay, Runnable runnable) {
        scheduled(delay, runnable, true);
    }

    public static void defaultClosableScheduled(Runnable runnable) {
        closableScheduled(5, runnable);
    }

    public static void syncClosableScheduled(long delay, Runnable runnable) {
        try {
            runnable.run();
        } catch (Throwable e) {
            closableScheduled(delay, runnable);
        }
    }

    public static void defaultSyncClosableScheduled(Runnable runnable) {
        syncClosableScheduled(5, runnable);
    }

    public static void scheduled(long delay, Runnable runnable, boolean shutdown) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            try {
                runnable.run();
                if (shutdown) {
                    scheduledExecutorService.shutdown();
                }
            } catch (Throwable e) {
                log.warn("scheduled error", e);
            }
        }, 0, delay, TimeUnit.SECONDS);
    }

    public static void scheduled(long delay, Runnable runnable) {
        scheduled(delay, runnable, false);
    }

    public static void defaultScheduled(Runnable runnable) {
        scheduled(60, runnable, false);
    }

}
